/**
 * Created by zhangqi on 2015/4/22.
 * id: 生成表单容器的id
 * @name 表单的字段名
 * @label 表单的显示信息
 * @type 表单的类型
 * @value 表单的值
 * @isEdit 表单是否课编辑
 * @className 特殊class样式
 * @maxlength 对文本框限制8个字符的长度输入
 * @isMust 是否显示必填星号
 * data:[
 {name:"userName",label:"用户名",type:"text",value:"张三",isEdit:true,className:"xxx",maxlength:8,isMust:true,algin:"right"},
 {name:"age",label:"年龄",type:"text",value:"26",isEdit:true},
 {name:"sex",label:"性别",type:"treeSelect",treeJsonArr:[{id:"0",name:"男"},{id:"1",name:"女"}]},
 {name:"id",label:"",type:"hidden",value:"111"},
 {name:"isOpen",label:"是否启用",type:"switch",value:"1"},  //选中是
 {name:"email",label:"邮箱",type:"text",value:"webzhangqi@qq.com"},
 {name:"joinTime",label:"入职时间",type:"text",value:"2015-04-01",className:"Wdate"} //文本框可以加 className字段 多个class用英文空格隔开
 {name:"treeName",label:"树下拉",type:"treeSelect",value:"test",treeJsonArr:[]} //树下拉控件
 ]
 * minHeight:300 //表单高度 默认300px
 *  showRow:1 //1为单列显示，2为双列显示 （默认为单列）
 *  formComplete:function(){}  //表单初始化完成的回调
 */

    require("./autoForm/autoForm.css");  //样式
    //是否组件
    require("../../plugins/bootstrap-switch/bootstrap-switch.css");
    require("../../plugins/bootstrap-switch/bootstrap-switch");
     //单选下拉框
    require("../../plugins/dayhrDropSelect/dayhrDropSelect.css");
    var dayhrDropSelect = require("../../plugins/dayhrDropSelect/dayhrDropSelect");
     //多选下拉框
    require("../../plugins/dayhrDropSelect/dayhrDropMultipleSelect.css");
    var dayhrDropMulSelect = require("../../plugins/dayhrDropSelect/dayhrDropMultipleSelect.js");
    var Ajax = require("../../plugins/ajax");
    //日历控件
    require("../../plugins/My97DatePicker/WdatePicker");
    //表单验证
    require('../../plugins/jquery.validator/local/zh_CN');

    require("../../plugins/artDialog/ui-dialog.css"); //artDialog弹窗
    require("../../plugins/artDialog/dialog-plus.js");

    var tools = require("../../plugins/tools.js"); //工具

    //kindeditor编辑器
    require("../../plugins/kindeditor/themes/default/default.css");
    require("../../plugins/kindeditor/kindeditor.all.min.js");

    var AutoForm = function () {
        this.init.apply(this, arguments);
    };
    AutoForm.prototype = {
        /** 构造函数 */
        constructor: AutoForm,
        options:{
             id:"" //容器的id
            ,data:[]  //表单数据
            ,minHeight:200 //表单高度 默认300px
            ,showRow:1 //1为单列显示，2为双列显示
            ,formComplete:null //表单初始化完成的回调
        },
        init: function (options) {
            this.options = $.extend({},this.options,options);
            if(!this.options.id){
                throw "请传入容器的id";return;
            }
            this.element = $("#"+ this.options.id);
            this.isCompleteWidthClick  = false; //是否表单初始化完成包含手动click触发，还是表单自动初始化完成的
            this.initDom();
        },
        /**
         * 初始化DOM
         * */
        initDom:function(){
            var t = this;
            if(!t.options.data.length){
                throw "请传入表单数据";return;
            }
            var aHtml = [];
            var aHtmlHidden = [];
            var $form = $("<form style='min-height: "+ t.options.minHeight+"px;' class='auto-form'></form>");
            var showRow = 12;
            if(t.options.showRow == 1){  //单列布局
                showRow = 12;
            }else if(t.options.showRow == 2){ //双列布局
                showRow = 6;
            }

            /*自动化判断是单列显示还是双列显示*/
            if(t.options.data.length >10){
                showRow = 6;
            }

            for(var i= 0;i<t.options.data.length;i++){
                var item = t.options.data[i];
                if(!item.type){
                    throw "请传入表单类型";break;return false;
                }
                switch (item.type){
                    //文本框
                    case "text":
                        var _str = '<div class="auto-form-row auto-form-'+showRow+'" data-selectType="text">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <input type="text" '+((item.isEdit || item.isEdit===undefined)?'':'readonly')+' class="text form-control '+(item.className?item.className:'')+'" name="'+item.name+'" value="'+((item.value ||item.value==0)?item.value:'')+'"  maxlength="'+(item.maxlength?item.maxlength:'')+'" style="'+(item.align == "right"?"text-align:right;":"text-algin:left;")+'">'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    case "datetime":
                    case "date":
                    case "date_yyyy_MM_dd_HH_mm":
                    case "date_yyyy_MM_dd_HH":
                    case "date_yyyy_MM":
                    case "date_yyyy":
                    case "date_worktime":
                        var sDataShowVal = "";
                        if(item.value){
                            if(item.name == "date_from" || item.name == "date_to"){
                                if(item.value == "1900-01-01" || item.value == "2099-12-31"){
                                    sDataShowVal = "";
                                }else{
                                    sDataShowVal = item.value;
                                }
                            }else{
                                sDataShowVal = item.value;
                            }
                        }else{
                            sDataShowVal = "";
                        }
                        var _str = '<div class="auto-form-row auto-form-'+showRow+'" data-selectType="datetime">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <input type="text" class="text form-control Wdate '+(item.className?item.className:'')+'" name="'+item.name+'" value="'+sDataShowVal+'" data-type="'+item.type+'" data-value="'+(item.value?item.value:'')+'">'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    case "hidden":
                        var _str = '<input type="hidden" name="'+item.name+'" value="'+item.value+'">';
                        aHtmlHidden.push(_str);
                        break;
                    //tree下拉选择框或者是可填写其他值的树下拉(两种情况)，单选下拉框
                    case "treeSelect":
                    case "treeAdviceSelect":
                        var sId = (new Date()).getTime()+"-"+item.name+"-"+Math.ceil(Math.random()*100000000);
                        var _str = '<div class="auto-form-row auto-form-'+showRow+'" data-selectType="treeSelect">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <div class="dayhr_drop_select" id="drop'+ sId +'" data-treedataid="'+sId+'" data-name="'+item.name+'" data-value="'+(item.value?item.value:"")+'" data-isallowother="'+(item.type=="treeAdviceSelect"?"true":"false")+'"></div>'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    //多选下拉框
                    case "treeMultipleSelect":
                        var sId = (new Date()).getTime()+"-"+item.name+"-"+Math.ceil(Math.random()*100000000);
                        var _str = '<div class="auto-form-row auto-form-'+showRow+'" data-selectType="treeMultipleSelect">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <div class="dayhr_drop_MulSelect" id="drop'+ sId +'" data-treedataid="'+sId+'" data-name="'+item.name+'" data-value="'+(item.value?item.value:"")+'"></div>'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    //是否开关
                    case "switch":
                        var sChecked = "";
                        if(item.value == "是" || item.value == "1"){
                            sChecked = "checked"
                        }
                        var _str = '<div class="auto-form-row auto-form-'+showRow+'" data-selectType="switch">'+
                            '        <label class="auto-form-left control-label" for="'+item.name+'" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '        <div class="auto-form-right">'+
                            '            <div class="switch">'+
                            '                <input class="switch-checkbox" name="'+item.name+'" type="checkbox" '+sChecked+' data-size="small" '+((!item.isEdit && (typeof item.isEdit!=="undefined"))?'disabled':'')+' />'+
                            '            </div>'+
                            '          </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    //多行文本框
                    case "textarea":
                        var _str = '<div class="auto-form-row auto-form-'+showRow+' auto-form-row-textarea" data-selectType="textarea">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <textarea '+((item.isEdit || item.isEdit===undefined)?'':'readonly')+' class="textarea form-control '+(item.className?item.className:'')+'" name="'+item.name+'"  style="height:'+(item.height?(item.height+'px'):'auto')+';" maxlength="'+(item.maxlength?item.maxlength:'')+'">' +((item.value ||item.value==0)?item.value:'')+'</textarea>'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    //富文本编辑器
                    case "editor":
                        var _str = '<div class="auto-form-row auto-form-'+showRow+' auto-form-row-textarea" data-selectType="editor">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <textarea '+((item.isEdit || item.isEdit===undefined)?'':'data-editable="readonly"')+' readonly class="textarea editor form-control '+(item.className?item.className:'')+'" name="'+item.name+'"  data-maxlength="'+(item.maxlength||"")+'"  data-height="'+(item.height||"")+'"  style="height: 20px;" title="点击弹出编辑">' +((item.value ||item.value==0)?item.value:'')+'</textarea>'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    //json编辑框
                    case "jsonMaker":
                    case "jsonMakerPersonal":
                        var _str = '<div class="auto-form-row auto-form-'+showRow+' auto-form-row-textarea" data-selectType="jsonMaker">'+
                            '                <label for="'+item.name+'" class="auto-form-left control-label" title="'+item.label+'">'+(item.isMust?'<span class="auto-form-muststar">*</span>':'')+item.label+'</label>'+
                            '                <div class="auto-form-right">'+
                            '                    <textarea readonly class="textarea jsonMaker form-control '+(item.className?item.className:'')+'" name="'+item.name+'"  style="height:'+(item.height?(item.height+'px'):'auto')+';cursor:pointer;" data-type="'+item.type+'" title="点击弹出编辑" >' +((item.value)?item.value:'')+'</textarea>'+
                            '                </div>'+
                            '        </div>';
                        aHtml.push(_str);
                        break;
                    default :
                        //

                }
            }
            $form.html(aHtml.join("")+aHtmlHidden.join(""));
            t.element.empty().append($form);
            //$form.find(".text").css({width:($form.find(".auto-form-right:first").width()-14)+"px",padding:"0 5px"});
            t.$form = $form;
            t.initFormPlugins($form); //初始化控件
            if(typeof t.options.formComplete == "function"){
                t.options.formComplete(t.$form);
            }
        },
        /**
         * 初始化表单控件
         * */
        initFormPlugins:function($form){
            var t = this;
            //初始化表单是否控件
            if($form.find(".switch").length){
                $form.find(".switch").find(".switch-checkbox").bootstrapSwitch();  //设置是否选中: $(".switch-checkbox").bootstrapSwitch("state",true);  ,获取选中的情况：$(".switch-checkbox").bootstrapSwitch("state");
            }
            //日历框控件初始化
            if($form.find(".Wdate").length){
                $form.find(".Wdate").each(function(){
                    var that = this;
                    var sDateFmt = "yyyy-MM-dd"; //默认是日期型的
                    var sDateType = $(this).attr("data-type");
                    if(sDateType == "datetime"){
                        sDateFmt = "yyyy-MM-dd HH:mm:ss";
                    } //如果是时间型的
                    else if(sDateType == "date_worktime"){
                        sDateFmt = "H:mm";
                    }else if(sDateType == "date_yyyy_MM_dd_HH_mm"){
                        sDateFmt = "yyyy-MM-dd HH:mm";
                    }else if(sDateType == "date_yyyy_MM_dd_HH"){
                        sDateFmt = "yyyy-MM-dd HH";
                    }else if(sDateType == "date_yyyy_MM"){
                        sDateFmt = "yyyy-MM";
                    }else if(sDateType == "date_yyyy"){
                        sDateFmt = "yyyy";
                    }
                    if($(this).val() && $(this).val() == "current"){
                        $(this).val(tools.dateFormat((new Date()),sDateFmt));
                    }

                    var afterDatePicked = function(){
                        //如果选择值后就关闭显示错误消息
                        if($.trim($(that).val())){
                            $(that).parent().find(".msg-box").hide(); //隐藏错误提示框
                        }
                    };

                    //如果同时存在 date_from和date_to的情况
                    if($form.find("input[name='date_from']").length && $form.find("input[name='date_to']").length){
                        var sName = $(this).attr("name");
                        if(sName == "date_from"){
                            $(this).off("focus").on("focus",function(){
                                WdatePicker({dateFmt:sDateFmt,maxDate:$form.find("input[name='date_to']").val(),onpicked:afterDatePicked});
                            });
                        }else if(sName == "date_to"){
                            $(this).off("focus").on("focus",function(){
                                WdatePicker({dateFmt:sDateFmt,minDate:$form.find("input[name='date_from']").val(),onpicked:afterDatePicked});
                            });
                        }else{
                            $(this).off("focus").on("focus",function(){
                                WdatePicker({dateFmt:sDateFmt,onpicked:afterDatePicked});
                            });
                        }
                    }else{
                        $(this).off("focus").on("focus",function(){
                            WdatePicker({dateFmt:sDateFmt,onpicked:afterDatePicked});
                        });
                    }
                });
            }

            //初始化下拉tree控件
            if($form.find(".dayhr_drop_select").length){
                $form.find(".dayhr_drop_select").each(function(i){
                    var that = this;
                    var sName = $(this).attr("data-name");
                    var _data = [];
                    var _keyValueBean = {};
                    var _isEdit;
                    var iForm; //第几个表单项
                    for(var i=0;i< t.options.data.length;i++){
                        var item = t.options.data[i];
                        if(sName == item.name){
                            _data = item.treeJsonArr;
                            _keyValueBean = item.keyValueBean;
                            _isEdit = item.isEdit; // 是否可编辑
                            iForm = i;
                        }
                    }
                    var tempDrop = new dayhrDropSelect({
                        id:$(this).attr("id"),
                        width:180,
                        maxHeight:250,
                        selectType:"single",
                        data:_data,
                        name:sName,
                        isEdit:_isEdit, // 是否可编辑
                        keyValueBean:_keyValueBean,
                        isAllowOther:$(this).attr("data-isallowother") == "true"?true:false, //是否可以填其他值
                        onSelected:function(oConditionBean,type){
                            //如果选择值后就关闭显示错误消息
                            if(oConditionBean.value){
                                $(that).find(".msg-box").hide();
                            }
                            //如果表单下拉项没有点击过，就判断是否被点击
                            if(!t.isCompleteWidthClick){
                                if(type == "click"){
                                    t.isCompleteWidthClick = true;
                                }
                            }
                            //下拉树选中之后的回调
                            var pageLayer = layer.load(1, {shade: [0.001,'#ffffff']}); //启用loading遮罩
                            var i = 0; //从第一个树开始
                            function updateOtherSeletTree(item){
                                //最后一个下拉项
                                if(i>=t.options.data.length){
                                    layer.close(pageLayer);//关闭loading遮罩
                                    //如果表单下拉项没有被点击过，就在最后一个执行完成回调
                                    if(!t.isCompleteWidthClick){
                                        if(typeof t.options.formComplete == "function"){
                                            t.options.formComplete(t.$form);
                                        }
                                    }
                                    return;
                                }
                                //找到子下拉 , oConditionBean.key与当前树的options.name相等
                                if(item.keyValueBean && item.keyValueBean.conditionId == oConditionBean.key){
                                    var oSend = item.keyValueBean;
                                    oSend.conditionBean = {key:oConditionBean.key,value:oConditionBean.value};
                                    Ajax.ApiTools().getKeyValueData({
                                        data:oSend,
                                        success:function(data){
                                            if(item.type == "treeSelect"){
                                                data.beans && data.beans.length && item.dayhrDropSelect.updateTreeJson(data.beans); //更新子树
                                                var $dayhrDropSelect = $form.find(".dayhr_drop_select[data-name='"+item.name+"']");
                                                item.dayhrDropSelect.setValue($dayhrDropSelect.attr("data-value"));
                                            }
                                            i++;
                                            updateOtherSeletTree(t.options.data[i]);
                                        }
                                    });
                                }else{
                                    //如果没找到就直接下一个
                                    i++;
                                    updateOtherSeletTree(t.options.data[i]);
                                }
                            }
                            updateOtherSeletTree(t.options.data[i]);
                        }
                    });
                    tempDrop.setValue($(this).attr("data-value"));
                    t.options.data[iForm]["dayhrDropSelect"] = tempDrop;
                });
            }

            //初始化多选下拉tree控件
            if($form.find(".dayhr_drop_MulSelect").length){
                $form.find(".dayhr_drop_MulSelect").each(function(i){
                    var sName = $(this).attr("data-name");
                    var _data = [];
                    var _keyValueBean = {};
                    var _isEdit;
                    var iForm; //第几个表单项
                    var _isShowSearchbox;
                    for(var i=0;i< t.options.data.length;i++){
                        var item = t.options.data[i];
                        if(!item.isShowSearchbox){_isShowSearchbox=false;}
                        if(sName == item.name){
                            _data = item.treeJsonArr;
                            _keyValueBean = item.keyValueBean;
                            _isEdit = item.isEdit; // 是否可编辑
                            _isShowSearchbox=item.isShowSearchbox;//是否可搜索
                            iForm = i;
                        }
                    }
                    var tempDrop = new dayhrDropMulSelect({
                        id:$(this).attr("id")
                        ,width:180
                        ,maxHeight:250
                        ,data:_data
                        ,name:sName
                        ,isEdit:_isEdit // 是否可编辑
                        ,keyValueBean:_keyValueBean
                        ,isShowSearchbox:_isShowSearchbox//是否可搜索
                    });
                    tempDrop.setValue($(this).attr("data-value"));
                    t.options.data[iForm]["dayhrDropMulSelect"] = tempDrop;
                });
            }

            //json编辑器控件
            $form.find("textarea.jsonMaker").each(function(){
                //普通管理员隐藏高级json编辑框
                if($(this).attr("data-type") == "jsonMakerPersonal"){
                    $(this).parent().parent().hide();
                }
                $(this).on("click",function(){
                    var that =  this;
                    var pageLayer = layer.load(1, {shade: [0.3,'#ffffff']}); //启用loading遮罩
                    require.async("js/modules/jsonMarker.js",function(JsonMarker){
                        new JsonMarker({$ele:$(that),$form:$form,oLayer:pageLayer});
                    });
                });
            });


            //富文本编辑器
            $form.find("textarea.editor").on("click",function () {
                var that = this;
                var editor;
                var editorId = "autoForm_editor_" + (new Date()).getTime();
                var editorDialog = dialog({
                    title:"编辑器"
                    ,ok:function () {
                        if(editor){
                            $(that).val(editor.html());
                            editorDialog.close().remove(); //关闭弹窗
                        }
                        return false;
                    }
                    ,cancel:function () {

                    }
                    ,content:'<div class="autoForm_editor_wrap" style="width:600px;height:auto;"><textarea id="'+editorId+'" name="content" style="width:100%;height:300px;border: 1px solid #bcbcbc;"></textarea></div>'
                }).showModal();

                editor = KindEditor.create('#'+editorId, {
                    resizeType:1,
                    allowPreviewEmoticons : false,
                    newlineTag:'br',
                    items : [
                        'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                        'removeformat','clearhtml', '|', 'justifyleft', 'justifycenter', 'justifyright','|','fullscreen']
                    ,afterCreate:function(){
                        setTimeout(function(){
                            if($(that).val()){
                                editor.html($(that).val());
                            }
                            editor.focus();
                        },100);
                    }
                });

            });


        }


    }

    module.exports = AutoForm;


